﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmartMathLibrary
{
    /// <summary>
    /// This class represents a mathematic polynomial for complex numbers.
    /// </summary>
    [Serializable]
    public class ComplexPolynomial : AbstractComplexPolynomial, IComplexPolynomial, IComplexFunction
    {
        /// <summary>
        /// The components of the polynomial.
        /// </summary>
        private List<ComplexPolynomialComponent> components;

        /// <summary>
        /// Initializes a new instance of the <see cref="ComplexPolynomial"/> class.
        /// </summary>
        public ComplexPolynomial()
        {
            this.components = new List<ComplexPolynomialComponent>();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ComplexPolynomial"/> class.
        /// </summary>
        /// <param name="poly">The complex polynomial to clone.</param>
        public ComplexPolynomial(ComplexPolynomial poly)
        {
            if (poly == (ComplexPolynomial) null)
            {
                throw new ArgumentNullException("poly");
            }

            this.components = poly.Components;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ComplexPolynomial"/> class.
        /// </summary>
        /// <param name="items">The number of items to create.</param>
        public ComplexPolynomial(int items)
        {
            this.components = new List<ComplexPolynomialComponent>();

            for (int i = 0; i < items; i++)
            {
                this.components.Add(new ComplexPolynomialComponent(new ComplexNumber(0), 0));
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ComplexPolynomial"/> class.
        /// </summary>
        /// <param name="components">The list of components for the complex polynomial.</param>
        public ComplexPolynomial(List<ComplexPolynomialComponent> components)
        {
            if (components == (List<ComplexPolynomialComponent>) null)
            {
                throw new ArgumentNullException("components");
            }

            this.components = components;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ComplexPolynomial"/> class.
        /// </summary>
        /// <param name="data">The array of components for the complex polynomial.</param>
        public ComplexPolynomial(ComplexPolynomialComponent[] data)
        {
            if (data == (ComplexPolynomialComponent[]) null)
            {
                throw new ArgumentNullException("data");
            }

            this.components = new List<ComplexPolynomialComponent>();

            foreach (ComplexPolynomialComponent p in data)
            {
                this.components.Add(p);
            }
        }

        /// <summary>
        /// Gets or sets the components of the complex polynomial.
        /// </summary>
        /// <value>The components of the complex polynomial.</value>
        public List<ComplexPolynomialComponent> Components
        {
            get { return components; }
        }

        /// <summary>
        /// Gets the rank of the polynomial.
        /// </summary>
        /// <value>The rank of the polynomial.</value>
        public double Rank
        {
            get
            {
                this.Sort();
                return this.components[this.components.Count - 1].Exponent;
            }
        }

        /// <summary>
        /// Sets the component at a specified position.
        /// </summary>
        /// <param name="index">The specified position where the value should be set.</param>
        /// <param name="component">The component to set.</param>
        public void SetComponentAt(int index, ComplexPolynomialComponent component)
        {
            this.components[index] = component;
        }

        /// <summary>
        /// Gets a component at a specified position.
        /// </summary>
        /// <param name="index">The specified position from which the component should be returned.</param>
        /// <returns>The component of the polynomial at the specified position.</returns>
        public ComplexPolynomialComponent GetComponentAt(int index)
        {
            return this.components[index];
        }

        /// <summary>
        /// Gets the polynomial with the smallest rank.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The polynomial with the smallest rank.</returns>
        public static ComplexPolynomial GetMinimumRank(ComplexPolynomial a, ComplexPolynomial b)
        {
            if (a == (ComplexPolynomial) null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == (ComplexPolynomial) null)
            {
                throw new ArgumentNullException("b");
            }

            if (a.Rank < b.Rank)
            {
                return a;
            }

            return b;
        }

        /// <summary>
        /// Gets the polynomial with the biggest rank.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The polynomial with the biggest rank.</returns>
        public static ComplexPolynomial GetMaximumRank(ComplexPolynomial a, ComplexPolynomial b)
        {
            if (a == (ComplexPolynomial) null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == (ComplexPolynomial) null)
            {
                throw new ArgumentNullException("b");
            }

            if (a.Rank < b.Rank)
            {
                return b;
            }

            return a;
        }

        /// <summary>
        /// Checks if a specified rank exists.
        /// </summary>
        /// <param name="value">The rank to check.</param>
        /// <returns>True if the rank exists in the polynomial otherwise, false.</returns>
        public bool ExistRank(double value)
        {
            foreach (ComplexPolynomialComponent c in this.components)
            {
                if (c.Exponent == value)
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Adds a new component to the polynomial at the front of it.
        /// </summary>
        /// <param name="component">The component to add.</param>
        public void AddInFrontOf(ComplexPolynomialComponent component)
        {
            this.components.Add(component);
        }

        /// <summary>
        /// Sorts this polynomial by ranks.
        /// </summary>
        public void Sort()
        {
            int min = 0;
            List<ComplexPolynomialComponent> tempuri = new List<ComplexPolynomialComponent>();

            while (this.components.Count > 0)
            {
                min = this.GetMinimumExponentIndex();
                tempuri.Add(this.components[min]);
                this.components.RemoveAt(min);
            }

            this.components = tempuri;
        }

        /// <summary>
        /// Gets the minimum index of the current polynomial.
        /// </summary>
        /// <returns>The minimum index of the current polynomial.</returns>
        private int GetMinimumExponentIndex()
        {
            int index = 0;
            double remind = Double.MaxValue;

            for (int i = 0; i < this.components.Count; i++)
            {
                if (this.components[i].Exponent < remind)
                {
                    index = i;
                    remind = this.components[i].Exponent;
                }
            }

            return index;
        }

        /// <summary>
        /// Adds the ranks of another polynomial to the current instance.
        /// </summary>
        /// <param name="poly">The polynomial from which the ranks should be added.</param>
        private void AddRanks(ComplexPolynomial poly)
        {
            for (int i = 0; i < poly.Components.Count; i++)
            {
                if (!this.ExistRank(poly.Components[i].Exponent))
                {
                    this.AddInFrontOf(new ComplexPolynomialComponent(new ComplexNumber(0), poly.Components[i].Exponent));
                }
            }
        }

        /// <summary>
        /// Calculates the polynomial with a specified value for x.
        /// </summary>
        /// <param name="x">The specified value for x.</param>
        /// <returns>The result of the polynomial with the specified value for x.</returns>
        public ComplexNumber SolveAt(double x)
        {
            ComplexNumber result = new ComplexNumber();

            foreach (ComplexPolynomialComponent c in this.components)
            {
                result += c.CalulateValue(x);
            }

            return result;
        }

        /// <summary>
        /// Calculates the polynomial with a specified value for x.
        /// </summary>
        /// <param name="x">The specified value for x.</param>
        /// <returns>The result of the polynomial with the specified value for x.</returns>
        public override ComplexNumber SolveAt(ComplexNumber x)
        {
            if (x == (ComplexNumber)null != false)
                throw new ArgumentException("x == (ComplexNumber)null != false", "x");

            ComplexNumber result = new ComplexNumber();

            foreach (ComplexPolynomialComponent c in this.components)
            {
                result += c.CalulateValue(x);
            }

            return result;
        }

        /// <summary>
        /// Creates the first derivative of the polynomial.
        /// </summary>
        /// <returns>Returns the derivative of the polynomial.</returns>
        public ComplexPolynomial Derivative()
        {
            ComplexPolynomialComponent[] tempuri = new ComplexPolynomialComponent[this.components.Count];

            this.components.CopyTo(tempuri);

            ComplexPolynomial result = new ComplexPolynomial(tempuri);

            for (int i = 0; i < result.Components.Count; i++)
            {
                result.Components[i] = result.Components[i].Derivative();
            }

            return result;
        }

        /// <summary>
        /// Removes all zero coefficients in the current polynomial.
        /// </summary>
        public void RemoveZeroCoefficients()
        {
            int i = 0;

            while (i < this.components.Count)
            {
                if (this.components[i].Coefficient == new ComplexNumber(0, 0))
                {
                    this.components.RemoveAt(i);
                }
                else
                {
                    i++;
                }
            }
        }

        /// <summary>
        /// Copies the current instance of the polynomial.
        /// </summary>
        /// <returns>The current instance of the polynomial.</returns>
        public ComplexPolynomial Copy()
        {
            ComplexPolynomialComponent[] tempuri = new ComplexPolynomialComponent[this.components.Count];

            this.components.CopyTo(tempuri);

            return new ComplexPolynomial(tempuri);
        }

        /// <summary>
        /// Implements the operator ==.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator ==(ComplexPolynomial a, ComplexPolynomial b)
        {
            if (System.Object.ReferenceEquals(a, b))
            {
                return true;
            }

            if (((object) a == null) || ((object) b == null))
            {
                return false;
            }

            if (a.Rank != b.Rank)
            {
                return false;
            }

            for (int i = 0; i < a.Components.Count; i++)
            {
                if (a.Components[i] != b.Components[i])
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Implements the operator !=.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator !=(ComplexPolynomial a, ComplexPolynomial b)
        {
            return !(a == b);
        }

        /// <summary>
        /// Implements the operator +.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static ComplexPolynomial operator +(ComplexPolynomial a, ComplexPolynomial b)
        {
            if (a == (ComplexPolynomial) null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == (ComplexPolynomial) null)
            {
                throw new ArgumentNullException("b");
            }

            a.AddRanks(b);
            b.AddRanks(a);
            a.Sort();
            b.Sort();

            for (int i = 0; i < a.Components.Count; i++)
            {
                a.Components[i] += b.Components[i];
            }

            return a;
        }

        /// <summary>
        /// Implements the operator -.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static ComplexPolynomial operator -(ComplexPolynomial a, ComplexPolynomial b)
        {
            if (a == (ComplexPolynomial) null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == (ComplexPolynomial) null)
            {
                throw new ArgumentNullException("b");
            }

            a.AddRanks(b);
            b.AddRanks(a);
            a.Sort();
            b.Sort();

            for (int i = 0; i < a.Components.Count; i++)
            {
                a.Components[i] -= b.Components[i];
            }

            return a;
        }

        /// <summary>
        /// Implements the operator *.
        /// </summary>
        /// <param name="a">The first polynomial.</param>
        /// <param name="b">The second polynomial.</param>
        /// <returns>The result of the operator.</returns>
        public static ComplexPolynomial operator *(ComplexPolynomial a, ComplexPolynomial b)
        {
            if (a == (ComplexPolynomial) null)
            {
                throw new ArgumentNullException("a");
            }

            if (b == (ComplexPolynomial) null)
            {
                throw new ArgumentNullException("b");
            }

            ComplexPolynomial result = new ComplexPolynomial(a.Components.Count + b.Components.Count + 1);

            a.AddRanks(b);
            b.AddRanks(a);
            a.Sort();
            b.Sort();

            for (int i = 0; i < a.Components.Count; i++)
            {
                for (int j = 0; j < b.Components.Count; j++)
                {
                    result.Components[i + j].Exponent = a.Components[i].Exponent + b.Components[j].Exponent;
                }
            }

            for (int i = 0; i < a.Components.Count; i++)
            {
                for (int j = 0; j < b.Components.Count; j++)
                {
                    result.Components[i + j].AddCoefficient(a.Components[i] * b.Components[j]);
                }
            }

            return result;
        }

        /// <summary>
        /// Compares the current instance of a polynomial to another one.
        /// </summary>
        /// <param name="compare">The polynomial to compare.</param>
        /// <returns>True if the polynomials are even otherwise, false.</returns>
        public bool CompareTo(ComplexPolynomial compare)
        {
            return this == compare;
        }

        /// <summary>
        /// Multiplies the polynomial with a scalar.
        /// </summary>
        /// <param name="scalar">The scalar value.</param>
        public void MultiplyWithScalar(int scalar)
        {
            this.MultiplyWithScalar((double) scalar);
        }

        /// <summary>
        /// Multiplies the polynomial with a scalar.
        /// </summary>
        /// <param name="scalar">The scalar value.</param>
        public void MultiplyWithScalar(double scalar)
        {
            for (int i = 0; i < this.components.Count; i++)
            {
                this.components[i].Coefficient *= scalar;
            }
        }

        /// <summary>
        /// Multiplies the polynomial with a scalar.
        /// </summary>
        /// <param name="scalar">The scalar value.</param>
        public void MultiplyWithScalar(ComplexNumber scalar)
        {
            if (scalar == (ComplexNumber)null != false)
                throw
                  new ArgumentException("scalar == (ComplexNumber)null != false", "scalar");

            for (int i = 0; i < this.components.Count; i++)
            {
                this.components[i].Coefficient *= scalar;
            }
        }

        /// <summary>
        /// Divides the polynomial through a scalar.
        /// </summary>
        /// <param name="scalar">The scalar value.</param>
        public void DivideWithScalar(int scalar)
        {
            this.DivideWithScalar((double) scalar);
        }

        /// <summary>
        /// Divides the polynomial through a scalar.
        /// </summary>
        /// <param name="scalar">The scalar value.</param>
        public void DivideWithScalar(double scalar)
        {
            for (int i = 0; i < this.components.Count; i++)
            {
                this.components[i].Coefficient /= scalar;
            }
        }

        /// <summary>
        /// Determines whether the polynomial [has only even exponents].
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if the polynomial [has only even exponents]; otherwise, <c>false</c>.
        /// </returns>
        public bool HasOnlyEvenExponents()
        {
            foreach (ComplexPolynomialComponent c in this.components)
            {
                if (c.Exponent % 2 != 0)
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Determines whether the polynomial [has only odd exponents].
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if the polynomial [has only odd exponents]; otherwise, <c>false</c>.
        /// </returns>
        public bool HasOnlyOddExponents()
        {
            return !(this.HasOnlyEvenExponents());
        }

        /// <summary>
        /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
        /// <returns>
        /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
        /// </returns>
        /// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception>
        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        /// <summary>
        /// Serves as a hash function for a particular type.
        /// </summary>
        /// <returns>
        /// A hash code for the current <see cref="T:System.Object"/>.
        /// </returns>
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        /// <summary>
        /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </returns>
        public override string ToString()
        {
            String result = "";

            this.Sort();

            for (int i = this.Components.Count - 1; i >= 0; i--)
            {
                result += this.Components[i].ToString() + " + ";
            }

            if (result.Length > 3)
            {
                result = result.Substring(0, result.Length - 3);
            }

            return result;
        }
    }
}